<?php
namespace app\index\model;

use app\index\model\Role;
use app\common\model\SuperModel;

class Menu extends SuperModel {

	protected $connection = 'db_config_dragon';

	/**
	 * 初始化
	 *
	 * @return   void
	 */
	protected function initialize() {

		parent::initialize();
		$this->table = 'menu';

	}

	/**
	 * 是否是叶子节点
	 * @DateTime 2018-02-11
	 * @param    [type] $value [description]
	 * @return   [type]
	 */
	public function getLeafAttr($value) {

		$isLeaf = [
			1 => true,
			0 => false,
		];
		
		return $isLeaf[$value];
	}

	/**
	 * 列表(主键列表，条件数组，闭包查询)
	 *
	 * @param    array $param 查询条件
	 * @return   void
	 */
	public function doList($param = null) {

		try {

			//查询数据，按照父级菜单升序，同级菜单升序

			if (empty($param)) {

				$result = self::all(function ($query) {
					$query->order('pid asc, m_order asc');
				});
			} else {

				$result = self::all(function ($query) use ($param) {
					$query->where($param)->order('pid asc, m_order asc');
				});
			}

			$rows = [];

			foreach ($result as $data) {
				$item = $data->getData();
				$item['leaf'] = $data->getAttr('leaf'); //访问获取器
				$item['expanded'] = true;
				$item['checked'] = false;
				array_push($rows, $item);
			}
			//返回结果
			$res = array();

			$total = count($rows);

			if ($total > 0) {
				$res['rows'] = $rows;
				$res['total'] = $total;
			} else {
				$res['total'] = 0;
				$res['rows'] = array();
			}
			//请求返回
			return ($res);

		} catch (\Exception $e) {
			throw new \think\Exception('异常消息:' . $e->getMessage());
		}
	}

	/**
	 * 列表(主键列表，条件数组，闭包查询)
	 *
	 * @param    array $param 查询条件
	 * @return   void
	 */
	public function doMenuList($role_id = null) {

		try {

			$map['status'] = 1;

			if($role_id){
				$role = new Role();
				$record = $role::get($role_id);
				$map['id'] =  ['in',$record->getData('menu_ids')];
			}

			$result = self::all(function ($query) use($map) {
				$query->where($map)->order('pid asc, m_order asc');
			});

			$rows = [];

			foreach ($result as $data) {
				$item = $data->getData();
				$item['leaf'] = $data->getAttr('leaf'); //访问获取器
				$item['expanded'] = true;
				array_push($rows, $item);
			}

			//返回结果

			$res = array();

			$total = count($rows);

			if ($total > 0) {
				$res['rows'] = $rows;
				$res['total'] = $total;
			} else {
				$res['total'] = 0;
				$res['rows'] = array();
			}
			//请求返回
			return ($res);

		 } catch (\Exception $e) {
		 	throw new \think\Exception('异常消息:' . $e->getMessage());
		 }
	}
}
